﻿
using Consul;
using MediatR;
using Microsoft.IdentityModel.Tokens;
using MyMES.Domain.W.Liststructure;
using MyMES.Error;
using MyMES.Infrastructure.Interface;
using MyMES.Read.API.Application.Commends.W.realize;
using System.IdentityModel.Tokens.Jwt;
using System.Runtime.CompilerServices;
using System.Security.Claims;
using System.Text;

namespace MyMES.Read.API.Application.CommendHandlers.W.realize
{
    public class GetUserCommandHandlers : IRequestHandler<GetUserCommands, APIResult<List<UserInfo>>>
    {
        private readonly IBaseRepository<UserInfo> userRepository;
        private readonly IConfiguration configuration;

        public GetUserCommandHandlers(IBaseRepository<UserInfo> userRepository, IConfiguration configuration)
        {
            this.userRepository = userRepository;
            this.configuration = configuration;
        }



        /// <summary>
        /// 生成 JWT Token（令牌）
        /// </summary>
        /// <returns></returns>
        private string CreateTokenString()
        {
            //私钥
            var secretByte = Encoding.UTF8.GetBytes(configuration["JwtSetting:secretByte"]);

      /*      var claims = new List<Claim>()
        {
            new Claim("uname", uname)
         //   new Claim("UId", "123")
        };*/
            // 非对称加密
            var signingKey = new SymmetricSecurityKey(secretByte);
            // 使用256 生成数字签名
            var signingCredentials = new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256);
            // 生成Token
            var token = new JwtSecurityToken(
                issuer: configuration["JwtSetting:issuer"],
                audience: configuration["JwtSetting:audience"],
                expires: DateTime.Now.AddDays(1), // 一天后过期
                signingCredentials: signingCredentials
               /* claims: claims*/
            );
            // 生成token 字符串
            var strToken = new JwtSecurityTokenHandler().WriteToken(token);
            return strToken;
        }

        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<APIResult<List<UserInfo>>> Handle(GetUserCommands request, CancellationToken cancellationToken)
        {
            APIResult<List<UserInfo>> result = new APIResult<List<UserInfo>>();
            result.Code = APIEnum.登录成功;
            result.Msg = "登录成功";
            string sql = $"select * from UserInfo where UserName ='{request.UserName}' and Password = '{request.Password}'";
            var list = await userRepository.SelectAsync(sql);
            var token= CreateTokenString();
            result.Token = "Bearer"+" "+token;
            result.data = list;
            return result;
        }
    }
}
